package com.tensquare.articlecrawler.task;

import com.tensquare.articlecrawler.pipeline.ArticleDbPipeline;
import com.tensquare.articlecrawler.pipeline.ArticleTxtPipeline;
import com.tensquare.articlecrawler.processor.ArticleProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.scheduler.RedisScheduler;

/**
 * 文章爬取任务类
 */
@Component
public class ArticleTask {

    @Autowired
    private ArticleProcessor articleProcessor;

    @Autowired
    private ArticleDbPipeline articleDbPipeline;

    @Autowired
    private ArticleTxtPipeline articleTxtPipeline;

    @Autowired
    private RedisScheduler redisScheduler;

   /* *//**
     * 秒 分 时 日 月 星期
     *//*
    @Scheduled(cron = "0 19 11 * * ?")
    public void aiTask(){
        articleDbPipeline.setChannelId("ai");

        Spider.create(articleProcessor)
                .addUrl("https://www.csdn.net/nav/ai")
                .addPipeline(articleDbPipeline)
                .setScheduler(redisScheduler)
                .start();
    }*/

    /**
     * 控制爬虫的开关
     */
    @Scheduled(cron = "40 28 15 * * ?")
    public void aiTask(){
        articleDbPipeline.setChannelId("ai");
        articleTxtPipeline.setChannelId("ai");

        Spider spider = Spider.create(articleProcessor)
                .addUrl("https://www.csdn.net/nav/ai")
                .addPipeline(articleDbPipeline)
                .addPipeline(articleTxtPipeline)
                .setScheduler(redisScheduler);

        //开启
        spider.start();


        /*//设置等待时间
        try {
            Thread.sleep(20*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //关闭
        spider.stop();*/
    }

    @Scheduled(cron = "10 49 15 * * ?")
    public void dbTask() {
        articleDbPipeline.setChannelId("db");
        articleTxtPipeline.setChannelId("db");

        Spider spider = Spider.create(articleProcessor)
                .addUrl("https://blog.csdn.net/nav/db")
                .addPipeline(articleDbPipeline)
                .addPipeline(articleTxtPipeline)
                .setScheduler(redisScheduler);

        //开启
        spider.start();
    }

    @Scheduled(cron = "0 51 15 * * ?")
    public void webTask() {
        articleDbPipeline.setChannelId("web");
        articleTxtPipeline.setChannelId("web");

        Spider spider = Spider.create(articleProcessor)
                .addUrl("https://blog.csdn.net/nav/web")
                .addPipeline(articleDbPipeline)
                .addPipeline(articleTxtPipeline)
                .setScheduler(redisScheduler);

        //开启
        spider.start();
    }
}
